// -----------------------------------------------
// Author:     code34 nicolas_boiteux@yahoo.fr
// Edited by:  Neumatic
// Warcontext: Civil drive car across the map
// -----------------------------------------------
if (!isServer) exitWith {};

private [
	"_find",
	"_vehicle",
	"_position",
	"_typeof",
	"_group",
	"_unit",
	"_exit",
	"_vehicles",
	"_target"
];

_unit = _this select 0;

_vehicles = nearestObjects [_unit, ["LandVehicle"], 300];
if (count _vehicles == 0) exitWith {
	_unit setVariable ["civilrole", "civil", true];
};

diag_log format ["WARCONTEXT: BUILD 1 DRIVER - FAME: %1", wcfame];
_target = wctownlocations call BIS_fnc_selectRandom;

_exit = false;
while {((alive _unit) and !_exit)} do {
	if (vehicle _unit == _unit) then {
		_find = false;

		_vehicles = nearestObjects [_unit, ["LandVehicle"], 300];
		{
			if ((count (crew _x) == 0) and !_find and (damage _x < 0.9)) then {
				_find = true;
				_vehicle = _x;
			};
		} foreach _vehicles;

		if (_find) then {
			while {((_unit distance _vehicle > 10) and (alive _unit) and (alive _vehicle) and !(locked _vehicle))} do {
				_unit doMove (position _vehicle);
				_unit setVariable ["destination", (position _vehicle), false];
				sleep 20;
			};

			if ((count (crew _vehicle) == 0) and (alive _unit) and (alive _vehicle) and !(locked _vehicle)) then {
				_position = position _unit;
				_typeof = typeOf _unit;
				_unit removeAllEventHandlers "Killed";
				_unit setPos [0,0];
				_unit setDamage 1;
				deleteVehicle _unit;
				_group = createGroup civilian;
				_unit = _group createUnit [_typeof, [0,0], [], 0, "FORM"];
				_vehicle setFuel 1;
				_vehicle setDamage 0;
				_unit assignAsDriver _vehicle;
				[_unit] orderGetIn true;
				_unit moveInDriver _vehicle;
			};
		} else {
			_unit setVariable ["civilrole", "civil", true];
			_exit = true;
		};
	} else {
		if (position _unit distance position _target > 150) then {
			_unit doMove position _target;
			sleep 30;
		} else {
			_target = wctownlocations call BIS_fnc_selectRandom;
		};
	};
	sleep 5;
};